const authorize = (scope, isOne = false, isMust = false) => {
    if (!scope || !authorizeObj[scope]) {
        return console.error('请传输需要获取权限的 scope，详见',
            'https://uniapp.dcloud.net.cn/api/other/authorize.html#scope-%E5%88%97%E8%A1%A8')
    }
    return new Promise(async (resolve, reject) => {
        let hasAuthorize = await getAuthorize(scope)
        if (hasAuthorize) {
            resolve()
        } else {
            uni.authorize({
                scope: `scope.${scope}`,
                success: (authorizeRes) => {
                    resolve()
                },
                fail: (authorizeErr) => {
                    if (!isOne) {
                        showModal(resolve, reject, scope, isMust)
                    } else {
                        reject()
                    }
                }
            })
        }
    })
}
const showModal = (resolve, reject, scope, isMust) => {
    uni.showModal({
        title: '温馨提示',
        content: `获取${authorizeObj[scope]}失败，是否进入设置页开启您的权限？`,
        success: (showModalRes) => {
            if (showModalRes.confirm) {
                uni.openSetting({
                    success: (openSettingRes) => {
                        if (openSettingRes.authSetting[`scope.${scope}`]) {
                            resolve()
                        } else {
                            if (isMust) {
                                showModal(resolve, reject, scope, isMust)
                            } else {
                                reject()
                            }
                        }
                    }
                });
            } else {
                reject()
            }
        }
    })
}

//查看是否授权
const getAuthorize = (scope) => {
    return new Promise((resolve, reject) => {
        uni.getSetting({
            success(res) {
                resolve(res.authSetting[`scope.${scope}`])
            }
        })
    })
}
let authorizeObj = {
    'userLocation': '精确地理位置权限',
    'userFuzzyLocation': '模糊地理位置权限',
    'userLocationBackground': '后台定位权限',
    'record': '麦克风权限',
    'camera': '摄像头权限',
    'bluetooth': '蓝牙权限',
    'writePhotosAlbum': '添加到相册权限',
    'addPhoneContact': '添加到联系人权限',
    'addPhoneCalendar': '添加到日历权限',
    'werun': '微信运动步数权限',
    'address': '通讯地址权限',
    'invoiceTitle': '发票抬头权限',
    'invoice': '获取发票权限',
    'userInfo': '用户信息权限'
}


export default authorize
